package com.itheima.service.serviceimpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.dao.InspectionUnitDao;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.InspectionUnitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class InspectionUnitServiceImpl implements InspectionUnitService {

    @Autowired
    private InspectionUnitDao inspectionUnitDao;

    @Override
    public List<CheckGroup> getAllInspectionUnit() {
        List<CheckGroup> list = inspectionUnitDao.findAll();
        return list;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckGroup> p = inspectionUnitDao.findPage(queryPageBean);
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Transactional
    public void addInspectionUnit(CheckGroup checkGroup, List<Integer> checkitemIds) {
        inspectionUnitDao.addInspectionUnit(checkGroup);
        Integer id = checkGroup.getId();
        log.info("id:{}", id);
        log.info("checkitemIds:{}", checkitemIds);
        //新增检查组与检查项的关联关系
        inspectionUnitDao.addInspectionUnitAndCheckItem(id, checkitemIds);
    }

    @Transactional
    public void editInspectionUnit(CheckGroup checkGroup, List<Integer> checkitemIds) {
        //修改检查组数据
        inspectionUnitDao.editInspectionUnit(checkGroup);
        Integer id = checkGroup.getId();
        //删除中间表数据
        inspectionUnitDao.deleteInspectionUnitAndCheckItem(id);
        //新增检查组与检查项的关联关系
        inspectionUnitDao.addInspectionUnitAndCheckItem(id, checkitemIds);
    }

    @Override
    public CheckGroup findById(Integer id) {
        return inspectionUnitDao.findById(id);
    }

    @Transactional
    public void deleteInspectionUnit(Integer id) {
        //删除中间表数据
        inspectionUnitDao.deleteInspectionUnitAndCheckItem(id);
        //删除中间表数据
        inspectionUnitDao.deleteInspectionUnitAndSetmeal(id);
        //删除检查组数据
        inspectionUnitDao.deleteInspectionUnit(id);

    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
        return inspectionUnitDao.findCheckGroupIdsBySetmealId(setmealId);
    }




}
